package com.senjoeson.teamfriends.fragment;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.senjoeson.teamfriends.R;
import com.senjoeson.teamfriends.adapter.TeamMessageAdapter;
import com.senjoeson.teamfriends.base.BaseFragment;
import com.senjoeson.teamfriends.bean.Friend;
import com.senjoeson.teamfriends.bean.FriendMessage;
import com.senjoeson.teamfriends.bean.User;
import com.senjoeson.teamfriends.utils.ALog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * @author senjoeson
 * @date 2018/4/25
 */

public class FriendFragment extends BaseFragment {

    @BindView(R.id.recyclyerview)
    RecyclerView mRecyclyerview;
    List<FriendMessage> friendMessages = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_friend;
    }

    @Override
    protected void initData() {
        mRecyclyerview.setLayoutManager(new LinearLayoutManager(getContext()));
        final TeamMessageAdapter teamMessageAdapter = new TeamMessageAdapter(getActivity());
        mRecyclyerview.setAdapter(teamMessageAdapter);


        final User currentUser = BmobUser.getCurrentUser(User.class);

        BmobQuery<Friend> friendBmobQuery = new BmobQuery<>();
        friendBmobQuery.addWhereEqualTo("userid", currentUser.getObjectId());
        friendBmobQuery.findObjects(new FindListener<Friend>() {
            @Override
            public void done(List<Friend> list, BmobException e) {
                if (list != null) {
                    for (Friend friend : list) {
                        String nickname = friend.getNickname();
                        getMessageFromFriend(nickname);
                    }

                    getMessageFromFriend(currentUser.getNickname());
                    teamMessageAdapter.setDatas(friendMessages);
                    teamMessageAdapter.notifyDataSetChanged();
                }
            }
        });


    }

    /**
     * 检查所有朋友是否有动态  如果有就添加
     *
     * @param nickname 根据昵称查询
     */
    private void getMessageFromFriend(String nickname) {
        BmobQuery<FriendMessage> friendMessageBmobQuery = new BmobQuery<>();
        friendMessageBmobQuery.addWhereEqualTo("author_name", nickname);
        friendMessageBmobQuery.order("-time");
        friendMessageBmobQuery.findObjects(new FindListener<FriendMessage>() {
            @Override
            public void done(List<FriendMessage> list, BmobException e) {
                if (list != null && list.size() > 0) {
                    friendMessages.addAll(list);
                } else {
                    ALog.d("Empty data");
                }
            }
        });
    }

    @Override
    protected void initListener() {

    }


}
